package czk.concrent.protectpause;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/8/11 17:40
 */
public class ProtectPauseDemo {
    public static void main(String[] args) {
        /**
         * 创建downloader
         */
        DownLoader downLoader=new DownLoader();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 创建保护性对象
        ProtectPause protectPause=new ProtectPause();
        executorService.submit(()->{
            List pause = protectPause.pause(11*1000);
            System.out.println(pause.size());
        });
        executorService.submit(()->{
            try {
                List<String> download = downLoader.download();
                // 赋值给保护性暂停
                protectPause.change(download);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 执行完后在关闭线程
        executorService.shutdown();
    }
}

/**
 *
 */
class ProtectPause{
    private List list;

    /**
     * 保护性暂停
     * @param time 传入时间
     * @return
     */
    public List pause(long time){
        // 得到当前时间
        long currentTimeMillis = System.currentTimeMillis();
        // 定义过了多长时间
        long passedTime=0;
        while (list==null){
            if (passedTime>time){
                System.out.println("时间到了，不想再等了");
                break;
            }
            synchronized (this){
                // 继续等待
                try {
                    // 减去以前等待的时间
                    System.out.println("进入等待室");
                    wait(time-passedTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 虚假唤醒后经过的时间
                passedTime=System.currentTimeMillis()-currentTimeMillis;
            }
        }
        System.out.println("获取值成功");
        return list;
    }

    /**
     * 给list赋值
     * @param list 值
     */
    public void change(List list){
        synchronized (this){
            // 赋值
            this.list=list;
            // 唤醒其他线程
            notifyAll();
            System.out.println("唤醒其他线程");
        }
    }
}
